package com.project.movie.controller.order;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.movie.common.enums.ResultCode;
import com.project.movie.config.utils.ShiroUtils;
import com.project.movie.domain.*;
import com.project.movie.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 超级管理员
 * @version 1.0
 * @description: 订单controller
 * @date 2025/02/07 09:53
 */
@Controller
@ResponseBody
@RequestMapping("order")
public class MovieOrderController {

    @Autowired
    private MovieOrderService movieOrderService;
    @Autowired
    private MoviePriceService moviePriceService;
    @Autowired
    private MovieItemService movieItemService;
    @Autowired
    private MovieOfficeService movieOfficeService;
    @Autowired
    private MovieSliceService movieSliceService;
    @Autowired
    private MovieCinemaService movieCinemaService;

    /** 分页获取订单 */
    @PostMapping("getMovieOrderPage")
    public Result getMovieOrderPage(@RequestBody MovieOrder movieOrder) {
        Page<MovieOrder> page = new Page<>(movieOrder.getPageNumber(),movieOrder.getPageSize());
        QueryWrapper<MovieOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .like(StringUtils.isNotBlank(movieOrder.getTel()),MovieOrder::getTel,movieOrder.getTel())
                .like(StringUtils.isNotBlank(movieOrder.getEmail()),MovieOrder::getEmail,movieOrder.getEmail())
                .eq(movieOrder.getLookDate() != null, MovieOrder::getLookDate,movieOrder.getLookDate())
                .eq(StringUtils.isNotBlank(movieOrder.getItemId()),MovieOrder::getItemId,movieOrder.getItemId())
                .eq(StringUtils.isNotBlank(movieOrder.getUserId()),MovieOrder::getUserId,movieOrder.getUserId())
                .eq(StringUtils.isNotBlank(movieOrder.getPriceId()),MovieOrder::getPriceId,movieOrder.getPriceId())
                .eq(StringUtils.isNotBlank(movieOrder.getCinemaId()),MovieOrder::getCinemaId,movieOrder.getCinemaId())
                .eq(StringUtils.isNotBlank(movieOrder.getOfficeId()),MovieOrder::getOfficeId,movieOrder.getOfficeId())
                .eq(movieOrder.getPrice() != null,MovieOrder::getPrice,movieOrder.getPrice())
                .eq(StringUtils.isNotBlank(movieOrder.getSliceId()),MovieOrder::getSliceId,movieOrder.getSliceId())
                .eq(StringUtils.isNotBlank(movieOrder.getCreateBy()),MovieOrder::getCreateBy,movieOrder.getCreateBy())
                .eq(movieOrder.getCreateTime() != null,MovieOrder::getCreateTime,movieOrder.getCreateTime())
                .eq(StringUtils.isNotBlank(movieOrder.getUpdateBy()),MovieOrder::getUpdateBy,movieOrder.getUpdateBy())
                .eq(movieOrder.getUpdateTime() != null,MovieOrder::getUpdateTime,movieOrder.getUpdateTime());
        Page<MovieOrder> movieOrderPage = movieOrderService.page(page, queryWrapper);
        for (MovieOrder order : movieOrderPage.getRecords()) {
            MovieItem movieItem = movieItemService.getById(order.getItemId());
            MovieOffice office = movieOfficeService.getById(order.getOfficeId());
            MovieCinema cinema = movieCinemaService.getById(order.getCinemaId());
            order.setItemName(movieItem.getName());
            order.setCinemaName(cinema.getName());
            order.setOfficeName(office.getName());
            String[] split = order.getPriceId().split(",");
            List<String> index = new ArrayList<>();
            for (String id:split) {
                MoviePrice moviePrice = moviePriceService.getById(id);
                int row = moviePrice.getRowIndex() + 1;
                int column = moviePrice.getColumnIndex() + 1;
                index.add(row + "排" + column + "座");
            }
            order.setPriceName(StringUtils.join(index,","));
        }
        return Result.success(movieOrderPage);
    }

    @PostMapping("getMovieOrderPageByManager")
    public Result getMovieOrderPageByManager(@RequestBody MovieOrder movieOrder) {
        User userInfo = ShiroUtils.getUserInfo();
        QueryWrapper<MovieCinema> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(MovieCinema::getUserId,userInfo.getId());
        List<MovieCinema> cinemaList = movieCinemaService.list(wrapper);
        List<String> list = new ArrayList<>();
        for (MovieCinema movieCinema : cinemaList) {
            list.add(movieCinema.getId());
        }
        Page<MovieOrder> page = new Page<>(movieOrder.getPageNumber(),movieOrder.getPageSize());
        QueryWrapper<MovieOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .in(list.size() > 0,MovieOrder::getCinemaId,list)
                .like(StringUtils.isNotBlank(movieOrder.getTel()),MovieOrder::getTel,movieOrder.getTel())
                .like(StringUtils.isNotBlank(movieOrder.getEmail()),MovieOrder::getEmail,movieOrder.getEmail())
                .eq(movieOrder.getLookDate() != null, MovieOrder::getLookDate,movieOrder.getLookDate())
                .eq(StringUtils.isNotBlank(movieOrder.getItemId()),MovieOrder::getItemId,movieOrder.getItemId())
                .eq(StringUtils.isNotBlank(movieOrder.getUserId()),MovieOrder::getUserId,movieOrder.getUserId())
                .eq(StringUtils.isNotBlank(movieOrder.getPriceId()),MovieOrder::getPriceId,movieOrder.getPriceId())
                .eq(StringUtils.isNotBlank(movieOrder.getOfficeId()),MovieOrder::getOfficeId,movieOrder.getOfficeId())
                .eq(movieOrder.getPrice() != null,MovieOrder::getPrice,movieOrder.getPrice())
                .eq(StringUtils.isNotBlank(movieOrder.getSliceId()),MovieOrder::getSliceId,movieOrder.getSliceId())
                .eq(StringUtils.isNotBlank(movieOrder.getCreateBy()),MovieOrder::getCreateBy,movieOrder.getCreateBy())
                .eq(movieOrder.getCreateTime() != null,MovieOrder::getCreateTime,movieOrder.getCreateTime())
                .eq(StringUtils.isNotBlank(movieOrder.getUpdateBy()),MovieOrder::getUpdateBy,movieOrder.getUpdateBy())
                .eq(movieOrder.getUpdateTime() != null,MovieOrder::getUpdateTime,movieOrder.getUpdateTime());
        Page<MovieOrder> movieOrderPage = movieOrderService.page(page, queryWrapper);
        for (MovieOrder order : movieOrderPage.getRecords()) {
            MovieItem movieItem = movieItemService.getById(order.getItemId());
            MovieOffice office = movieOfficeService.getById(order.getOfficeId());
            MovieCinema cinema = movieCinemaService.getById(order.getCinemaId());
            order.setItemName(movieItem.getName());
            order.setCinemaName(cinema.getName());
            order.setOfficeName(office.getName());
            String[] split = order.getPriceId().split(",");
            List<String> index = new ArrayList<>();
            for (String id:split) {
                MoviePrice moviePrice = moviePriceService.getById(id);
                int row = moviePrice.getRowIndex() + 1;
                int column = moviePrice.getColumnIndex() + 1;
                index.add(row + "排" + column + "座");
            }
            order.setPriceName(StringUtils.join(index,","));
        }
        return Result.success(movieOrderPage);
    }

    @GetMapping("getMovieOrderByUserId")
    public Result getMovieOrderByUserId() {
        User user = ShiroUtils.getUserInfo();
        QueryWrapper<MovieOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(MovieOrder::getUserId,user.getId()).orderByDesc(MovieOrder::getCreateTime);
        List<MovieOrder> orderList = movieOrderService.list(queryWrapper);
        for (MovieOrder order : orderList) {
            MovieItem movieItem = movieItemService.getById(order.getItemId());
            MovieOffice office = movieOfficeService.getById(order.getOfficeId());
            MovieCinema cinema = movieCinemaService.getById(order.getCinemaId());
            order.setItemName(movieItem.getName());
            order.setCinemaName(cinema.getName());
            order.setOfficeName(office.getName());
            String[] split = order.getPriceId().split(",");
            List<String> index = new ArrayList<>();
            for (String id:split) {
                MoviePrice moviePrice = moviePriceService.getById(id);
                int row = moviePrice.getRowIndex() + 1;
                int column = moviePrice.getColumnIndex() + 1;
                index.add(row + "排" + column + "座");
            }
            order.setPriceName(StringUtils.join(index,","));
        }
        return Result.success(orderList);
    }

    @GetMapping("ticketChanges")
    public Result ticketChanges(@RequestParam("id")String id) {
        MovieOrder order = movieOrderService.getById(id);
        QueryWrapper<MovieSlice> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(MovieSlice::getItemId,order.getItemId())
                .eq(MovieSlice::getCinemaId,order.getCinemaId())
                .groupBy(MovieSlice::getLookDate);
        //获取排片列表
        List<MovieSlice> sliceList = movieSliceService.list(queryWrapper);
        //获取列表日期具体排片
        for (MovieSlice movieSlice : sliceList) {
            QueryWrapper<MovieSlice> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(MovieSlice::getItemId,order.getItemId())
                    .eq(MovieSlice::getCinemaId,order.getCinemaId())
                    .eq(MovieSlice::getLookDate,movieSlice.getLookDate());
            List<MovieSlice> movieSliceList = movieSliceService.list(wrapper);
            for (MovieSlice slice : movieSliceList) {
                MovieOffice office = movieOfficeService.getById(slice.getOfficeId());
                slice.setOfficeName(office.getName());
            }
            movieSlice.setMovieSlices(movieSliceList);
        }
        return Result.success(sliceList);
    }

    @PostMapping("/ticketChangesSubmit")
    @Transactional(rollbackFor = Exception.class)
    public Result ticketChangesSubmit(@RequestBody JSONObject jsonObject) {
        String orderId = jsonObject.getString("id");
        String sliceId = jsonObject.getString("sliceId");
        String priceId = jsonObject.getString("priceId");
        MovieOrder order = movieOrderService.getById(orderId);
        if (order.getState() == 2 || order.getState() == 1) {
            return Result.fail("不可退票");
        }
        MovieSlice slice = movieSliceService.getById(sliceId);
        order.setLookDate(slice.getLookDate());
        order.setSliceId(sliceId);
        order.setOfficeId(slice.getOfficeId());
        String[] split = order.getPriceId().split(",");
        //先把之前下单的状态改成未售出
        for (String id : split) {
            MoviePrice price = moviePriceService.getById(id);
            price.setState(1);
            moviePriceService.updateById(price);
        }
        //查询新的座位价格
        String[] strings = priceId.split(",");
        List<MoviePrice> list = new ArrayList<>();
        int total = 0;
        for (String string : strings) {
            MoviePrice price = moviePriceService.getById(string);
            price.setState(0);
            list.add(price);
            total += price.getPrice();
            moviePriceService.updateById(price);
        }
        order.setPriceId(priceId);
        order.setPrice(total);
        order.setStart(slice.getStart());
        order.setEnd(slice.getEnd());
        boolean update = movieOrderService.updateById(order);
        if (update) {
            return Result.success();
        } else {
            return Result.fail();
        }
    }

    /** 根据id获取订单 */
    @GetMapping("getMovieOrderById")
    public Result getMovieOrderById(@RequestParam("id")String id) {
        MovieOrder movieOrder = movieOrderService.getById(id);
        return Result.success(movieOrder);
    }

    /** 保存订单 */
    @PostMapping("saveMovieOrder")
    @Transactional(rollbackFor = Exception.class)
    public Result saveMovieOrder(@RequestBody MovieOrder movieOrder) {
        String priceId = movieOrder.getPriceId();
        String[] ids = priceId.split(",");
        for (String id : ids) {
            MoviePrice price = moviePriceService.getById(id);
            if (price.getState() == 0) {
                int row = price.getRowIndex() + 1;
                int column = price.getColumnIndex() + 1;
                return Result.fail(row + "排" + column + "座已售出,请返回重新选择");
            }
            price.setState(0);
            moviePriceService.updateById(price);
        }
        MovieSlice slice = movieSliceService.getById(movieOrder.getSliceId());
        MovieItem movieItem = movieItemService.getById(movieOrder.getItemId());
        MovieOffice office = movieOfficeService.getById(movieOrder.getOfficeId());
        MovieCinema cinema = movieCinemaService.getById(movieOrder.getCinemaId());
        movieOrder.setItemName(movieItem.getName());
        movieOrder.setCinemaName(cinema.getName());
        movieOrder.setOfficeName(office.getName());
        movieOrder.setEnd(slice.getEnd());
        boolean save = movieOrderService.save(movieOrder);
        if (save) {
            return Result.success();
        } else {
            return Result.fail(ResultCode.COMMON_DATA_OPTION_ERROR.getMessage());
        }
    }

    /** 编辑订单 */
    @PostMapping("editMovieOrder")
    @Transactional(rollbackFor = Exception.class)
    public Result editMovieOrder(@RequestBody MovieOrder movieOrder) {
        boolean save = movieOrderService.updateById(movieOrder);
        if (movieOrder.getState() == 1) {
            MovieOrder order = movieOrderService.getById(movieOrder.getId());
            //退票退坐
            String[] split = order.getPriceId().split(",");
            //先把之前下单的状态改成未售出
            for (String id : split) {
                MoviePrice price = moviePriceService.getById(id);
                price.setState(1);
                moviePriceService.updateById(price);
            }
        }
        if (save) {
            return Result.success();
        } else {
            return Result.fail(ResultCode.COMMON_DATA_OPTION_ERROR.getMessage());
        }
    }

    /** 删除订单 */
    @GetMapping("removeMovieOrder")
    public Result removeMovieOrder(@RequestParam("ids")String ids) {
        if (StringUtils.isNotBlank(ids)) {
            String[] asList = ids.split(",");
            for (String id : asList) {
                movieOrderService.removeById(id);
            }
            return Result.success();
        } else {
            return Result.fail("订单id不能为空！");
        }
    }

}
